import React, { useEffect, useState } from 'react'
import routes from '@/router'
import { useRoutes } from 'react-router-dom'
import { AppWrapper } from '@/style'
import { ConfigProvider } from 'antd'
// antd：中文化
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'

import { myShallowEqual, useMySelector } from '@/store'
import { createNewThemeConfig } from './utils/theme'
import useEncrypt from '@/hooks/use-encrypt'
import { localCache } from './utils/cache'
import { CacheType } from './global/constant'
import { addModuleToRoute } from './utils/menu-handle'

dayjs.locale('zh-cn')

function App() {
  // 保存公钥
  useEncrypt()

  const [myRoutes, setMyRoutes] = useState(routes)

  // 从store获取主题配置
  const { themeConfig, menuList } = useMySelector(
    (state) => ({
      themeConfig: state.app.themeConfig,
      menuList: state.app.menuList
    }),
    myShallowEqual
  )

  useEffect(() => {
    const localRoutes = localCache.getCache(CacheType.ROUTES)
    if (!localRoutes) return
    // 这里的3是写死的，那么配置中main必须放在第四个，位置严格要求
    if (routes[3]?.children) {
      const newRoutes = [...routes]
      const children = routes[3].children
      children?.splice(2, children?.length - 2)
      const newMainRoutes = addModuleToRoute(localRoutes)
      children.push(...newMainRoutes)
      newRoutes[3].children = children
      setMyRoutes(newRoutes)
    }
  }, [menuList])

  return (
    <ConfigProvider theme={createNewThemeConfig(themeConfig)}>
      <AppWrapper>{useRoutes(myRoutes)}</AppWrapper>
    </ConfigProvider>
  )
}

export default App
